if __name__ == '__main__':
    # 外部启动django的方法
    import sys, os
    from django.core.wsgi import get_wsgi_application

    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(base_dir)
    os.environ['DJANGO_SETTINGS_MODULE'] = 'drf_movie_rimi.settings'
    application = get_wsgi_application()

    from rest_framework import serializers
    from mytest.models import Mytest
    from rest_framework.serializers import ModelSerializer


    class MyTestSerializer(serializers.Serializer):
        name = serializers.CharField(max_length=20)
        age = serializers.IntegerField()

        # 重写save方法 让他验证成功后保存数据
        def create(self, validated_data):
            return Mytest.objects.create(**validated_data)

        # 重写update方法 让他验证成功后更新数据
        def update(self, instance, validated_data):
            instance.name = validated_data.get('name', instance.name)
            instance.name = validated_data.get('age', instance.age)
            instance.save()

            return instance


    class MyTestSerializer2(serializers.Serializer):
        name = serializers.CharField(max_length=20)
        age = serializers.IntegerField()
        id = serializers.IntegerField()

        # 重写update方法 让他验证成功后更新数据
        def update(self, instance, validated_data):
            id = validated_data.get('id')
            #获取manager
            obj = instance.objects.filter(pk=id)[0]
            #更新数据
            obj.name = validated_data.get('name', obj.name)
            obj.age = validated_data.get('age', obj.age)
            try:
                #保存更新
                obj.save()
            except Exception as e:
                x = e
                pass

            return obj


    data = Mytest.objects.all()[0]
    serializer_data = MyTestSerializer2(Mytest, data={'id':4,'name': '测试', 'age': 81})
    # 必须调用了is_valid之后才能调用save方法
    serializer_data.is_valid()
    serializer_data.save()
